# -*- coding: utf-8 -*-
"""
文本处理工具插件
提供各种文本处理功能
"""

import sys
import os
import base64
import hashlib
from urllib.parse import quote, unquote

# 添加父目录到路径，以便导入core模块
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from core.plugin_manager import BasePlugin


class TextToolsPlugin(BasePlugin):
    """文本处理工具插件"""
    
    def __init__(self):
        super().__init__()
        self.name = "text"
        self.version = "1.0.0"
        self.description = "文本处理工具，支持编码、解码、哈希等功能"
        
    def execute(self, args):
        """执行文本处理功能"""
        if not args:
            self.show_help()
            return True
            
        command = args[0].lower()
        text_args = args[1:] if len(args) > 1 else []
        
        if command == 'help':
            self.show_help()
        elif command == 'base64':
            self.handle_base64(text_args)
        elif command == 'url':
            self.handle_url_encode(text_args)
        elif command == 'hash':
            self.handle_hash(text_args)
        elif command == 'count':
            self.handle_count(text_args)
        elif command == 'case':
            self.handle_case_convert(text_args)
        else:
            print(f"未知的文本处理命令: {command}")
            print("输入 'text help' 查看可用命令")
            
        return True
        
    def handle_base64(self, args):
        """处理Base64编码/解码"""
        if len(args) < 2:
            print("用法: text base64 <encode|decode> <文本>")
            return
            
        operation = args[0].lower()
        text = ' '.join(args[1:])
        
        try:
            if operation == 'encode':
                encoded = base64.b64encode(text.encode('utf-8')).decode('utf-8')
                print(f"Base64编码结果: {encoded}")
            elif operation == 'decode':
                decoded = base64.b64decode(text.encode('utf-8')).decode('utf-8')
                print(f"Base64解码结果: {decoded}")
            else:
                print("操作必须是 'encode' 或 'decode'")
        except Exception as e:
            print(f"Base64操作失败: {e}")
            
    def handle_url_encode(self, args):
        """处理URL编码/解码"""
        if len(args) < 2:
            print("用法: text url <encode|decode> <文本>")
            return
            
        operation = args[0].lower()
        text = ' '.join(args[1:])
        
        try:
            if operation == 'encode':
                encoded = quote(text, safe='')
                print(f"URL编码结果: {encoded}")
            elif operation == 'decode':
                decoded = unquote(text)
                print(f"URL解码结果: {decoded}")
            else:
                print("操作必须是 'encode' 或 'decode'")
        except Exception as e:
            print(f"URL操作失败: {e}")
            
    def handle_hash(self, args):
        """处理哈希计算"""
        if len(args) < 2:
            print("用法: text hash <md5|sha1|sha256> <文本>")
            return
            
        hash_type = args[0].lower()
        text = ' '.join(args[1:])
        
        try:
            if hash_type == 'md5':
                result = hashlib.md5(text.encode('utf-8')).hexdigest()
            elif hash_type == 'sha1':
                result = hashlib.sha1(text.encode('utf-8')).hexdigest()
            elif hash_type == 'sha256':
                result = hashlib.sha256(text.encode('utf-8')).hexdigest()
            else:
                print("支持的哈希类型: md5, sha1, sha256")
                return
                
            print(f"{hash_type.upper()}哈希值: {result}")
        except Exception as e:
            print(f"哈希计算失败: {e}")
            
    def handle_count(self, args):
        """处理文本统计"""
        if not args:
            print("用法: text count <文本>")
            return
            
        text = ' '.join(args)
        
        char_count = len(text)
        char_count_no_space = len(text.replace(' ', ''))
        word_count = len(text.split())
        line_count = text.count('\n') + 1
        
        print(f"字符数（含空格）: {char_count}")
        print(f"字符数（不含空格）: {char_count_no_space}")
        print(f"单词数: {word_count}")
        print(f"行数: {line_count}")
        
    def handle_case_convert(self, args):
        """处理大小写转换"""
        if len(args) < 2:
            print("用法: text case <upper|lower|title|capitalize> <文本>")
            return
            
        operation = args[0].lower()
        text = ' '.join(args[1:])
        
        if operation == 'upper':
            result = text.upper()
            print(f"转换为大写: {result}")
        elif operation == 'lower':
            result = text.lower()
            print(f"转换为小写: {result}")
        elif operation == 'title':
            result = text.title()
            print(f"转换为标题格式: {result}")
        elif operation == 'capitalize':
            result = text.capitalize()
            print(f"首字母大写: {result}")
        else:
            print("支持的操作: upper, lower, title, capitalize")
            
    def show_help(self):
        """显示帮助信息"""
        print("\n=== 文本处理工具使用说明 ===")
        print("用法: text <命令> [参数...]")
        print("\n可用命令:")
        print("  base64 <encode|decode> <文本>  - Base64编码/解码")
        print("  url <encode|decode> <文本>     - URL编码/解码")
        print("  hash <md5|sha1|sha256> <文本>  - 计算哈希值")
        print("  count <文本>                   - 统计文本信息")
        print("  case <upper|lower|title|capitalize> <文本> - 大小写转换")
        print("\n示例:")
        print("  text base64 encode Hello")
        print("  text url decode %E4%B8%AD%E6%96%87")
        print("  text hash md5 password")
        print("  text count 这是一段测试文本")
        print("  text case upper hello world")
        
    def get_help(self):
        """获取插件帮助信息"""
        return f"{self.name}: {self.description}\n  用法: text <命令> [参数...]"